﻿using Microsoft.Win32;
using Rox;
using System;
using System.Diagnostics;
using System.IO;
using System.Management;
using System.Threading.Tasks;
using static Rox.Runtimes.LocalizedString;
using static Rox.Runtimes.LogLibraries;
namespace ReBuilderPatcher
{
    public class Program
    {
        public static string _App_Name = @"重构修补程序 (Re-Builder Patcher)";
        public static string _App_des = @"此应用程序旨在修补、优化和删除带有广告的程序";
        public static string _sgPath = @"C:\Program Files (x86)\SogouInput";
        public static string basePath_x86 = Path.Combine(_sgPath, "Components\\biz_center");
        public static string basePath_x64 = Path.Combine(_sgPath, "Components\\biz_center");
        public static string _QQ_Shell64 = @"C:\Program Files\Tencent\QQNT\qq_shell_extension_64.dll";
        public static string _QQ_Shell32 = @"C:\Program Files\Tencent\QQNT\qq_shell_extension_32.dll";
        public static string _biz_shell64 = @"biz_shellext64.dll";
        public static string _biz_shell32 = @"biz_shellext.dll";
        public static string _biz_notify = @"biz_notify.exe";
        public static string _pdf = @"C:\Users\Administrator\AppData\Local\sogoupdf";
        public static string _pdf_exe = @"pdfpreview.exe";
        public static string _pdf_host = @"prevhost.exe";
        public static string _pdf_exe_all = Path.Combine(_pdf, _pdf_exe);
        public static string _pdf_handle = @"pdfpreviewhandler.dll";
        public static string _pdf_handle_all = Path.Combine(_pdf, _pdf_handle);
        //public static string _360_untils = @"C:\Program Files (x86)\360\360Safe\Utils";
        //public static string _360_mgr = @"C:\Program Files (x86)\360\360Safe\SoftMgr";
        //public static string _360_utils32 = @"shell360Ext.dll";
        //public static string _360_utils64 = @"shell360Ext64.dll";
        //public static string _360_mgr32 = @"SoftMgrExt.dll";
        //public static string _360_mgr64 = @"SoftMgrExt64.dll";
        public static string _wps_basePath = @"C:\Users\Administrator\AppData\Roaming\Kingsoft\wps\addons\pool\win-i386";
        public static string _ip = @"\\192.168.0.82";
        public static string _net_path = Path.Combine(_ip, @"软件2");
        public static string _power_shadow = @"PowerShadow-32-8.5.5.exe";
        public static string _power_shadow_path = Path.Combine(_net_path, _power_shadow);
        public static string _directX = @"DirectX\DXSETUP.exe";
        public static string _directX_path = Path.Combine(_net_path, _directX);
        public static string _LAV = $@"LAVFilters-0.80-Installer.exe";
        public static string _LAV_path = Path.Combine(_net_path, _LAV);
        public static string _MPEG2 = $@"Microsoft.MPEG2VideoExtension_1.2.13.0_neutral_~_8wekyb3d8bbwe.AppxBundle";
        public static string _MPEG2_path = Path.Combine(_net_path, _MPEG2);
        public static string _HEVC = $@"Microsoft.HEVCVideoExtension_2.4.25.0_neutral_~_8wekyb3d8bbwe.AppxBundle";
        public static string _HEVC_path = Path.Combine(_net_path, _HEVC);
        public static string _HEIF = $@"Microsoft.HEIFImageExtension_1.2.23.0_neutral_~_8wekyb3d8bbwe.AppxBundle";
        public static string _HEIF_path = Path.Combine(_net_path, _HEIF);
        public static string _AV1 = $@"Microsoft.AV1VideoExtension_2.0.4.0_neutral_~_8wekyb3d8bbwe.AppxBundle";
        public static string _AV1_path = Path.Combine(_net_path, _AV1);
        public static string _active = @"$Windows & Office 激活工具(选择永久使用).exe";
        public static string _active_path = Path.Combine(_net_path, _active);
        public static string _Extension = @"Extension";
        public static string _Extension_path = Path.Combine(_net_path, _Extension);
        public static string _Extension_cmd = Path.Combine(_Extension_path, @"!copy.cmd");
        public static string _reg1 = @"HKEY_CLASSES_ROOT\*\shellex\ContextMenuHandlers\PcyybAiCtxMenuShellExt";
        public static string _reg2 = @"HKEY_CLASSES_ROOT\*\shellex\ContextMenuHandlers\PcyybContextnMenu";
        public static string _reg3 = @"HKEY_CLASSES_ROOT\Drive\ShellEx\ContextMenuHandlers\PcyybContextnMenu";
        public static string _reg4 = @"HKEY_CLASSES_ROOT\CLSID\{645FF040-5081-101B-9F08-00AA002F954E}\shell\深度清理垃圾";
        public static string _reg5 = @"HKEY_CLASSES_ROOT\CLSID\{645FF040-5081-101B-9F08-00AA002F954E}\shellex\ContextMenuHandlers\master_context_menu";
        public static string _reg6 = @"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Sogou.Ime.SysToast.Biz";
        public static string _reg7 = @"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Sogou.Ime.SysToast.Biz.68DA5384";
        //
        //
        //
        public static bool _Ext = false;
        public static bool _lav = false;
        public static bool _hevc = false;
        public static bool _heif = false;
        public static bool _av1 = false;
        public static bool _mpeg2 = false;
        public static bool _diX = false;
        public static bool _pshadow = false;
        public static bool _win = false;
        public static bool _skip = false;
        public static void Main(string[] args)
        {
            Console.Title = _App_Name;
            WriteLog.Info($"正在准备 {_App_Name}");
            WriteLog.Info(_App_des);
            WriteLog.Info("命令行参数:" + Environment.CommandLine);
            if (args.Length > 0)
            {
                foreach (var arg in args)
                {
                    string a = arg.Trim();
                    a = a.ToLower();
                    if (a.StartsWith("-skip"))
                    {
                        _skip = true;
                        continue;
                    }
                    if (a.StartsWith("-ip="))
                    {
                        _ip = arg.Substring(4);
                        continue;
                    }
                    if (a.StartsWith("-sgpath="))
                    {
                        _sgPath = arg.Substring(8);
                        continue;
                    }
                    if (a.StartsWith("-hevc="))
                    {
                        _HEVC_path = arg.Substring(6);
                        _hevc = true;
                        continue;
                    }
                    if (a.StartsWith("-mpeg2="))
                    {
                        _MPEG2_path = arg.Substring(7);
                        _mpeg2 = true;
                        continue;
                    }
                    if (a.StartsWith("-heif="))
                    {
                        _HEIF_path = arg.Substring(6);
                        _heif = true;
                        continue;
                    }
                    if (a.StartsWith("-av1="))
                    {
                        _AV1_path = arg.Substring(5);
                        _av1 = true;
                        continue;
                    }
                    if (a.StartsWith("-lav="))
                    {
                        _LAV_path = arg.Substring(5);
                        _lav = true;
                        continue;
                    }
                    if (a.StartsWith("-directx="))
                    {
                        _directX_path = arg.Substring(9);
                        _diX = true;
                        continue;
                    }
                    if (a.StartsWith("-powershadow="))
                    {
                        _power_shadow_path = arg.Substring(13);
                        _pshadow = true;
                        continue;
                    }
                    if (a.StartsWith("-active="))
                    {
                        _active_path = arg.Substring(8);
                        _win = true;
                        continue;
                    }
                    if (a.StartsWith("-ext="))
                    {
                        _Extension_path = arg.Substring(5);
                        _Ext = true;
                        break;
                    }
                }
            }
            if (Killbiz_notify(basePath_x86))
                WriteLog.Info($"已成功卸载组件: {basePath_x86}\\{_biz_notify}");
            else
            {
                WriteLog.Error($"未能卸载组件: {basePath_x86}\\{_biz_notify}");
                if (Killbiz_notify(basePath_x64))
                    WriteLog.Info($"已成功卸载组件: {basePath_x64}\\{_biz_notify}");
                else
                    WriteLog.Error($"未能卸载组件: {basePath_x64}\\{_biz_notify}");
            }
            if (KillsgShell(basePath_x86))
            {
                WriteLog.Info($"已成功卸载组件: {basePath_x86}\\{_biz_shell32}");
                WriteLog.Info($"已成功卸载组件: {basePath_x86}\\{_biz_shell64}");
            }
            else
            {
                WriteLog.Error($"未能卸载组件: {basePath_x86}\\{_biz_shell32}");
                WriteLog.Error($"未能卸载组件: {basePath_x86}\\{_biz_shell64}");
                if (KillsgShell(basePath_x64))
                {
                    WriteLog.Info($"已成功卸载组件: {basePath_x64}\\{_biz_shell32}");
                    WriteLog.Info($"已成功卸载组件: {basePath_x64}\\{_biz_shell64}");
                }
                else
                {
                    WriteLog.Error($"未能卸载组件: {basePath_x64}\\{_biz_shell32}");
                    WriteLog.Error($"未能卸载组件: {basePath_x64}\\{_biz_shell64}");
                }
            }

            if (IsQQExtExist())
            {
                WriteLog.Info($"发现 DLL 文件: {_QQ_Shell32}");
                WriteLog.Info($"发现 DLL 文件: {_QQ_Shell64}");
                bool a = UnregisterDll(_QQ_Shell32);
                bool b = UnregisterDll(_QQ_Shell64);
                if (a)
                    WriteLog.Info($"已成功卸载组件: {_QQ_Shell32}");
                else
                    WriteLog.Error($"未能卸载组件: {_QQ_Shell32}");
                if (b)
                    WriteLog.Info($"已成功卸载组件: {_QQ_Shell64}");
                else
                    WriteLog.Error($"未能卸载组件: {_QQ_Shell64}");
            }
            if (CheckRegistryKeyExists(_reg1))
            {
                if (RegDelete(_reg1))
                    WriteLog.Info($"已成功卸载注册表: {_reg1}");
                else
                    WriteLog.Error($"未能卸载注册表: {_reg1}");
            }

            if (CheckRegistryKeyExists(_reg2))
            {
                if (RegDelete(_reg2))
                    WriteLog.Info($"已成功卸载注册表: {_reg2}");
                else
                    WriteLog.Error($"未能卸载注册表: {_reg2}");
            }

            if (CheckRegistryKeyExists(_reg3))
            {
                if (RegDelete(_reg3))
                    WriteLog.Info($"已成功卸载注册表: {_reg3}");
                else
                    WriteLog.Error($"未能卸载注册表: {_reg3}");
            }

            if (CheckRegistryKeyExists(_reg4))
            {
                if (RegDelete(_reg4))
                    WriteLog.Info($"已成功卸载注册表: {_reg4}");
                else
                    WriteLog.Error($"未能卸载注册表: {_reg4}");
            }

            if (CheckRegistryKeyExists(_reg5))
            {
                if (RegDelete(_reg5))
                    WriteLog.Info($"已成功卸载注册表: {_reg5}");
                else
                    WriteLog.Error($"未能卸载注册表: {_reg5}");
            }

            if (CheckRegistryKeyExists(_reg6))
            {
                if (RegDelete(_reg6))
                    WriteLog.Info($"已成功卸载注册表: {_reg6}");
                else
                    WriteLog.Error($"未能卸载注册表: {_reg6}");
            }

            if (CheckRegistryKeyExists(_reg7))
            {
                if (RegDelete(_reg7))
                    WriteLog.Info($"已成功卸载注册表: {_reg7}");
                else
                    WriteLog.Error($"未能卸载注册表: {_reg7}");
            }
            // 设置自动更新开关（1=开启，0=关闭）
            Process.Start("reg", @"add ""HKCU\Software\SogouPY"" /v ""AutoUpdateEnabled"" /t REG_DWORD /d 0 /f");
            //  设置开机启动开关（1 = 开启，0 = 关闭）
            Process.Start("reg", @"add ""HKCU\Software\SogouPY"" /v ""AutoStartWithWindows"" /t REG_DWORD /d 0 /f");
            // 设置自动检查更新开关（1=开启，0=关闭）
            Process.Start("reg", @"add ""HKCU\Software\SogouPY"" /v ""UpdateAutoCheck"" /t REG_DWORD /d 0 /f");
            if (KillsgPDF())
            {
                WriteLog.Info($"已成功卸载PDF组件: {_pdf_exe_all}");
            }
            else
            {
                WriteLog.Error($"未能卸载PDF组件: {_pdf_exe_all}");
            }
            if (KillWPSPreview())
            {
                WriteLog.Info($"已成功卸载WPS预览组件");
            }
            else
            {
                WriteLog.Error($"未能卸载WPS预览组件");
            }

            if (!_skip)
            {
                // 异步执行方法并设置10秒超时，超时后直接跳过
                var task = Task.Run(() => TestNetwork());
                if (!task.Wait(5000))
                {
                    WriteLog.Warning("网络组件安装超时，跳过剩余操作...");
                    if (_heif)
                        if (InstallHEIF())
                            WriteLog.Info(LogKind.Process, $@"HEIF 解码器扩展 安装完成! ");
                        else
                            WriteLog.Error(LogKind.Process, $@"HEIF 解码器扩展 安装失败! ");

                    if (_hevc)
                        if (InstallHEVC())
                            WriteLog.Info(LogKind.Process, $@"H.265 解码器扩展 安装完成! ");
                        else
                            WriteLog.Error(LogKind.Process, $@"H.265 解码器扩展 安装失败! ");

                    if (_av1)
                        if (InstallAV1())
                            WriteLog.Info(LogKind.Process, $@"AV1 解码器扩展 安装完成! ");
                        else
                            WriteLog.Error(LogKind.Process, $@"AV1 解码器扩展 安装失败! ");

                    if (_diX)
                        if (OpenDirectX())
                            WriteLog.Info(LogKind.Process, $@"DirectX 安装完成! ");
                        else
                            WriteLog.Error(LogKind.Process, $@"DirectX 安装失败! ");
                    if (_mpeg2)
                        if (InstallMPEG2())
                            WriteLog.Info(LogKind.Process, $@"MPEG2 解码器扩展 安装完成! ");
                        else
                            WriteLog.Error(LogKind.Process, $@"MPEG2 解码器扩展 安装失败! ");

                    if (_win)
                        if (ActiveWindows())
                            WriteLog.Info("Windows已激活");
                        else
                            WriteLog.Error("Windows激活失败");
                    if (_lav)
                        if (!File.Exists(@"C:\Program Files (x86)\LAV Filters\x64\avcodec-lav-62.dll"))
                        {
                            if (Start(_LAV_path))
                                WriteLog.Info(LogKind.Process, $@"H.265 解码器 安装完成! ");
                            else
                                WriteLog.Error(LogKind.Process, $@"H.265 解码器 安装失败! ");
                        }
                    if (_Ext)
                        if (OpenExt())
                            WriteLog.Info(LogKind.Registry, $@"扩展 注册完成! ");
                        else
                            WriteLog.Error(LogKind.Registry, $@"扩展 注册失败! ");
                    if (_pshadow)
                        if (OpenPowerShadow())
                            WriteLog.Info(LogKind.Process, $@"影子系统 PowerShadow 安装完成! ");
                        else
                            WriteLog.Error(LogKind.Process, $@"影子系统 PowerShadow 安装失败! ");

                    return;
                    // 超时，执行跳过逻辑（此处为空表示直接跳过）
                }
                else
                    NetWorkSetup();
            }
            WriteLog.Info("完成!\n/////////////////////////////////////////////////////////////////////////////////");
            Console.ReadKey();
        }
        public static bool KillWPSPreview()
        {
            try
            {
                // 遍历pool目录下以"win-"开头的文件夹（如win-i386、win-x64等）
                // 在每个win-*目录下匹配以"pdfwspv_"开头的文件夹（包含版本号）
                foreach (var pdfDir in Directory.EnumerateDirectories(_wps_basePath, "pdfwspv_*"))
                {
                    // 拼接完整的dll路径并赋值给b
                    string b = Path.Combine(pdfDir, "pdfwspv.dll");
                    WriteLog.Info($"正在尝试卸载 WPS 预览组件: {b}");
                    // 执行卸载操作
                    if (UnregisterDll(b))
                    {
                        WriteLog.Info($"已成功卸载组件: {b}");
                        return true;
                    }
                    else
                    {
                        WriteLog.Error($"未能卸载组件: {b}");
                        // 尝试删除文件
                        if (File.Exists(b))
                            File.Delete(b);
                        return false;
                    }
                    // 若只需匹配第一个符合条件的路径，可在此处添加break;
                }
                return false;
            }
            catch (Exception e)
            {
                WriteLog.Error(_Exception_With_xKind("KillWPSPreview", e));
                return false;
            }

        }
        private static bool TestNetwork() => File.Exists(Path.Combine(_net_path, _power_shadow));
        public static bool OpenPowerShadow()
        {
            if (File.Exists(@"C:\Program Files (x86)\PowerShadow\App\PowerMaster.exe"))
            {
                WriteLog.Info("影子系统 已安装");
                return true;
            }
            WriteLog.Info($@"正在安装 影子系统 PowerShadow: {_power_shadow_path}");
            return Start(_power_shadow_path);
        }
        public static bool OpenDirectX()
        {
            if (File.Exists(@"C:\Windows\System32\d3dx9_27.dll"))
            {
                WriteLog.Info(@"DirectX 已安装");
                return true;
            }
            WriteLog.Info(LogKind.Process, $@"正在安装 DirectX: {_directX_path}");
            return Start(_directX_path);
        }
        public static bool ActiveWindows()
        {
            if (Windows.IsWindowsActivated())
            {
                WriteLog.Info(LogKind.System, "Windows 已激活");
                return true;
            }
            WriteLog.Info("正在激活 Windows......");
            return Start(_active_path, @"/windows /office /renewal /lock");
        }
        public static void NetWorkSetup()
        {
            if (OpenPowerShadow())
                WriteLog.Info(LogKind.Process, $@"影子系统 PowerShadow 安装完成! ");
            else
                WriteLog.Error(LogKind.Process, $@"影子系统 PowerShadow 安装失败! ");

            if (OpenDirectX())
                WriteLog.Info(LogKind.Process, $@"DirectX 安装完成! ");
            else
                WriteLog.Error(LogKind.Process, $@"DirectX 安装失败! ");
            if (OpenExt())
                WriteLog.Info(LogKind.Registry, $@"扩展 注册完成! ");
            else
                WriteLog.Error(LogKind.Registry, $@"扩展 注册失败! ");
            if (!File.Exists(@"C:\Program Files (x86)\LAV Filters\x64\avcodec-lav-62.dll"))
            {
                if (Start(_LAV_path))
                    WriteLog.Info(LogKind.Process, $@"H.265 解码器 安装完成! ");
                else
                    WriteLog.Error(LogKind.Process, $@"H.265 解码器 安装失败! ");
            }
            else
                WriteLog.Info("HEVC解码器已安装完成!");
            if (ActiveWindows())
                WriteLog.Info("Windows已激活");
            else
                WriteLog.Error("Windows激活失败");
            if (InstallHEVC())
                WriteLog.Info(LogKind.Process, $@"H.265 解码器扩展 安装完成! ");
            else
                WriteLog.Error(LogKind.Process, $@"H.265 解码器扩展 安装失败! ");
            if (InstallMPEG2())
                WriteLog.Info(LogKind.Process, $@"MPEG2 解码器扩展 安装完成! ");
            else
                WriteLog.Error(LogKind.Process, $@"MPEG2 解码器扩展 安装失败! ");

            if (InstallHEIF())
                WriteLog.Info(LogKind.Process, $@"HEIF 解码器扩展 安装完成! ");
            else
                WriteLog.Error(LogKind.Process, $@"HEIF 解码器扩展 安装失败! ");
            if (InstallAV1())
                WriteLog.Info(LogKind.Process, $@"AV1 解码器扩展 安装完成! ");
            else
                WriteLog.Error(LogKind.Process, $@"AV1 解码器扩展 安装失败! ");


        }
        private static bool InstallHEVC() => Start("powershell", "Add-AppxPackage " + _HEVC_path);
        private static bool InstallAV1() => Start("powershell", "Add-AppxPackage " + _AV1_path);
        private static bool InstallHEIF() => Start("powershell", "Add-AppxPackage " + _HEIF_path);
        private static bool InstallMPEG2() => Start("powershell", "Add-AppxPackage " + _MPEG2);

        public static bool OpenExt()
        {
            using (RegistryKey key = Registry.ClassesRoot.OpenSubKey("Godot.Project"))
            {
                if (key != null)
                {
                    return true;
                }
            }
            if (_Ext)
            {
                return Start(_Extension_cmd);
            }
            if (Rox.Runtimes.Directory_I.CopyDirectory(_Extension_path, Path.GetTempPath()))
            {
                WriteLog.Info(LogKind.System, $"复制 {_Extension_path} 到 {Path.GetTempPath()}成功");
            }
            else
            {
                WriteLog.Error(LogKind.System, $"复制 {_Extension_path} 到 {Path.GetTempPath()}失败");
                return false;
            }
            //string c = Path.Combine(Path.GetTempPath(), a, @"!copy.cmd");
            WriteLog.Info(LogKind.Registry, $@"正在注册 扩展: {_Extension_path}");
            Rox.Windows.Explorer.OpenFolderInExplorer(Path.Combine(Path.GetTempPath(), _Extension_path));
            // 循环等待直到注册表项存在
            WriteLog.Info("正在等待手动注册......");
            while (true)
            {
                using (RegistryKey key = Registry.ClassesRoot.OpenSubKey("Godot.Project"))
                {
                    if (key != null)
                    {
                        // 注册表项存在，跳出循环
                        WriteLog.Info(LogKind.Registry, $@"成功注册扩展");
                        break;
                    }

                    // 注册表项不存在，等待1秒后重试
                    System.Threading.Thread.Sleep(5000);
                }
            }
            return true;
        }
        public static bool IsQQExtExist()
        {
            if (File.Exists(_QQ_Shell32))
                return true;
            else
                return false;
        }
        public static bool KillsgPDF()
        {
            try
            {
                if (File.Exists(_pdf_exe_all))
                {
                    if (Taskkill(_pdf_exe))
                    {
                        WriteLog.Info($"已成功卸载组件: {_pdf_exe_all}");
                    }
                    else
                    {
                        WriteLog.Error($"未能卸载组件: {_pdf_exe_all}");
                    }
                    if (Taskkill(_pdf_host))
                    {
                        WriteLog.Info($"已成功卸载组件: {_pdf_exe_all}");
                    }
                    else
                    {
                        WriteLog.Error($"未能卸载组件: {_pdf_exe_all}");
                    }
                    if (UnregisterDll(_pdf_handle_all))
                    {
                        WriteLog.Info($"已成功卸载组件: {_pdf_handle_all}");
                    }
                    else
                    {
                        WriteLog.Error($"未能卸载组件: {_pdf_handle_all}");
                        return false;
                    }

                    Directory.Delete(_pdf, true);

                    if (!Directory.Exists(_pdf))
                    {
                        using (Process p = new Process())
                        {
                            p.StartInfo.FileName = "fsutil";
                            p.StartInfo.Arguments = $"file createnew \"{_pdf}\" 0";
                            p.StartInfo.UseShellExecute = false;
                            p.Start();
                            p.WaitForExit();
                            if (p.ExitCode != 0)
                            {
                                WriteLog.Error(LogKind.Process, _Exception_With_xKind("KillsgPDF"));
                                WriteLog.Error(LogKind.Process, $"返回值为 {p.ExitCode}");
                                return false;
                            }
                            else
                            {
                                WriteLog.Info(LogKind.Process, $"返回值为{p.ExitCode}");
                            }
                        }

                        if (Attrib(_pdf, "+S +H +R"))
                        {
                            WriteLog.Info(LogKind.System, $"已成功设置属性: {_pdf}");
                            return true;
                        }
                        else
                        {
                            WriteLog.Error(LogKind.System, $"未能设置属性: {_pdf}");
                            return false;
                        }
                    }
                    WriteLog.Error($"未能卸载PDF工具");
                    return false;
                }
                WriteLog.Warning("不存在PDF工具, 也许很干净");
                return false;
            }
            catch (Exception e)
            {
                WriteLog.Error(_Exception_With_xKind("KillsgPDF", e));
                return false;
            }
        }
        public static bool Start(string path)
        {
            if (!File.Exists(path))
            {
                WriteLog.Error($"未找到文件: {path}");
                return false;
            }

            try
            {
                using (Process p = new Process())
                {
                    p.StartInfo.FileName = path;
                    p.Start();
                    WriteLog.Info(LogKind.Process, $"{_PROCESS_STARTED}: {p.StartInfo.FileName} - {p.StartInfo.Arguments}\nPID: {p.Id}");
                    p.WaitForExit();
                    if (p.ExitCode != 0)
                    {
                        WriteLog.Error($"进程 {p.StartInfo.FileName} - {p.StartInfo.Arguments} 返回的值为 {p.ExitCode}");
                        return false;
                    }
                    else
                    {
                        WriteLog.Info(LogKind.Process, $"进程 {p.StartInfo.FileName} - {p.StartInfo.Arguments} 返回的值为 {p.ExitCode}");
                        return true;
                    }
                }
            }
            catch (Exception e)
            {
                WriteLog.Error(LogKind.Process, _Exception_With_xKind("Process.Start", e));
                return false;
            }
        }
        public static bool Start(string path, string args)
        {
            if (path == "powershell" || path == "cmd" || path == "attrib")
                goto go;
            if (!File.Exists(path))
            {
                WriteLog.Info($"未找到文件: {path}");
                return false;
            }
        go:
            try
            {
                using (Process p = new Process())
                {
                    p.StartInfo.FileName = path;
                    p.StartInfo.Arguments = args;
                    p.Start();
                    WriteLog.Info(LogKind.Process, $"{_PROCESS_STARTED}: {p.StartInfo.FileName} - {p.StartInfo.Arguments}\nPID: {p.Id}");
                    p.WaitForExit();
                    if (p.ExitCode != 0)
                    {
                        WriteLog.Error(LogKind.Process, $"进程 {p.StartInfo.FileName} - {p.StartInfo.Arguments} 返回的值为 {p.ExitCode}");
                        return false;
                    }
                    else
                    {
                        WriteLog.Info(LogKind.Process, $"进程 {p.StartInfo.FileName} - {p.StartInfo.Arguments} 返回的值为 {p.ExitCode}");
                        return true;
                    }
                }
            }
            catch (Exception e)
            {
                WriteLog.Error(LogKind.Process, _Exception_With_xKind("Process.Start", e));
                return false;
            }
        }

        public static bool RegDelete(string path)
        {
            using (Process p = new Process())
            {
                p.StartInfo.FileName = "reg";
                p.StartInfo.Arguments = $"delete {path} /f";
                p.StartInfo.CreateNoWindow = true;
                p.Start();
                p.WaitForExit();
                if (p.ExitCode != 0)
                {
                    WriteLog.Error(LogKind.Registry, $"返回的值: {p.ExitCode}");
                    return false;
                }
                else
                {
                    WriteLog.Info(LogKind.Registry, $"返回的值: {p.ExitCode}");
                    return true;
                }
            }
        }

        public static bool KillsgShell(string path)
        {
            // 获取所有子目录
            string[] subDirectories = Directory.GetDirectories(path);

            foreach (string dir in subDirectories)
            {
                // 检查是否存在目标DLL
                string dllPath32 = Path.Combine(dir, _biz_shell32);
                string dllPath64 = Path.Combine(dir, _biz_shell64);
                if (File.Exists(dllPath64))
                {
                    WriteLog.Info($"发现 DLL 文件：{dllPath64}");
                    WriteLog.Info($"发现 DLL 文件：{dllPath32}");
                    WriteLog.Info("正在执行卸载命令...");
                    WriteLog.Info($"正在尝试卸载 Shell...");

                    // 执行regsvr32卸载命令
                    bool success = UnregisterDll(dllPath64);
                    bool success32 = UnregisterDll(dllPath32);

                    if (!success)
                    {
                        WriteLog.Error($"卸载失败：{dllPath64}");
                        return false;
                    }
                    WriteLog.Info($"卸载成功：{dllPath64}");
                    if (!success32)
                    {
                        WriteLog.Error($"卸载失败：{dllPath32}");
                        return false;
                    }
                    WriteLog.Info($"卸载成功：{dllPath32}");

                }
            }
            return true;
        }

        public static bool Killbiz_notify(string dir)
        {
            try
            {
                string biz_path = Path.Combine(dir, _biz_notify);
                Taskkill(_biz_notify);
                File.Delete(biz_path);
                using (Process p = new Process())
                {
                    p.StartInfo.FileName = "fsutil";
                    p.StartInfo.Arguments = $"file createnew \"{biz_path}\" 0";
                    p.StartInfo.UseShellExecute = false;
                    p.Start();
                    p.WaitForExit();
                    if (p.ExitCode != 0)
                    {
                        WriteLog.Error(LogKind.Process, _Exception_With_xKind("Killbiz_notify"));
                        WriteLog.Error(LogKind.Process, $"返回值为 {p.ExitCode}");
                        return false;
                    }
                    else
                    {
                        WriteLog.Info(LogKind.Process, $"返回值为{p.ExitCode}");
                        Attrib(biz_path, "+S +H +R");
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog.Error(LogKind.Process, _Exception_With_xKind("Killbiz_notify", ex));
                return false;
            }
        }
        /// <summary>
        /// 检查注册表项是否存在
        /// </summary>
        /// <param name="fullRegistryPath">注册表项的完整路径，如"HKLM\SOFTWARE\Microsoft\Windows"</param>
        /// <returns>如果注册表项存在则返回true，否则返回false</returns>
        public static bool CheckRegistryKeyExists(string fullRegistryPath)
        {
            if (string.IsNullOrEmpty(fullRegistryPath))
            {
                WriteLog.Error(_Exception_With_xKind("CheckRegistryKeyExits", new ArgumentException("string 为 null")));
                return false;
            }

            // 分割路径，获取根键和子路径
            int firstBackslashIndex = fullRegistryPath.IndexOf('\\');
            if (firstBackslashIndex <= 0)
            {
                WriteLog.Error(_Exception_With_xKind("CheckRegistryKeyExists", new ArgumentException("无效的注册表路径格式，应类似\"HKLM\\SOFTWARE\\...\"")));
                return false;
            }

            string rootKeyName = fullRegistryPath.Substring(0, firstBackslashIndex);
            string subPath = fullRegistryPath.Substring(firstBackslashIndex + 1);

            // 获取根注册表项的RegistryHive
            if (!TryGetRegistryHive(rootKeyName, out RegistryHive hive))
            {
                WriteLog.Error(_Exception_With_xKind("CheckRegistryKeyExists", new ArgumentException($"无效的根键: {rootKeyName}")));
                return false;
            }

            try
            {
                // 检查64位视图
                using (RegistryKey rootKey64 = RegistryKey.OpenBaseKey(hive, RegistryView.Registry64))
                using (RegistryKey subKey64 = rootKey64.OpenSubKey(subPath, false))
                {
                    if (subKey64 != null)
                    {
                        WriteLog.Info(LogKind.Registry, $"{fullRegistryPath} 键存在 (64位视图)");
                        return true;
                    }
                }

                // 检查32位视图
                using (RegistryKey rootKey32 = RegistryKey.OpenBaseKey(hive, RegistryView.Registry32))
                using (RegistryKey subKey32 = rootKey32.OpenSubKey(subPath, false))
                {
                    if (subKey32 != null)
                    {
                        WriteLog.Info(LogKind.Registry, $"{fullRegistryPath} 键存在 (32位视图)");
                        return true;
                    }
                }

                // 两种视图都不存在
                WriteLog.Error(LogKind.Registry, $"{fullRegistryPath} 键不存在");
                return false;
            }
            catch (Exception ex)
            {
                WriteLog.Error(LogKind.Registry, _Exception_With_xKind("CheckRegistryKeyExists", ex));
                return false;
            }
        }

        /// <summary>
        /// 转换根键名称为RegistryHive
        /// </summary>
        private static bool TryGetRegistryHive(string rootKeyName, out RegistryHive hive)
        {
            hive = RegistryHive.CurrentUser;
            string key = rootKeyName.ToUpperInvariant();

            switch (key)
            {
                case "HKCR":
                case "HKEY_CLASSES_ROOT":
                    hive = RegistryHive.ClassesRoot;
                    return true;
                case "HKCU":
                case "HKEY_CURRENT_USER":
                    hive = RegistryHive.CurrentUser;
                    return true;
                case "HKLM":
                case "HKEY_LOCAL_MACHINE":
                    hive = RegistryHive.LocalMachine;
                    return true;
                case "HKU":
                case "HKEY_USERS":
                    hive = RegistryHive.Users;
                    return true;
                case "HKCC":
                case "HKEY_CURRENT_CONFIG":
                    hive = RegistryHive.CurrentConfig;
                    return true;
                default:
                    return false;
            }
        }

        public static bool Attrib(string path, string args)
        {
            using (Process p = new Process())
            {
                p.StartInfo.FileName = "attrib";
                p.StartInfo.Arguments = $"{path} {args}";
                p.Start();
                p.WaitForExit();
                if (p.ExitCode != 0)
                {
                    WriteLog.Error(LogKind.Process, _Exception_With_xKind("Attrib"));
                    return false;
                }
                else
                {
                    WriteLog.Info(LogKind.Process, $"返回的值 {p.ExitCode}");
                    return true;
                }
            }
        }
        /// <summary>
        /// 使用regsvr32卸载指定的DLL
        /// </summary>
        /// <param name="dllPath">DLL文件的完整路径</param>
        /// <returns>如果卸载成功则返回true，否则返回false</returns>
        static bool UnregisterDll(string dllPath)
        {
            try
            {
                // 创建进程启动信息
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = "regsvr32.exe",
                    Arguments = $"/u /s \"{dllPath}\"",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                };

                // 启动进程
                using (Process process = Process.Start(startInfo))
                {
                    WriteLog.Info(LogKind.Process, $"正在卸载: {dllPath}\n Process :{startInfo?.FileName} - {startInfo?.Arguments}\nPID: {process.Id}");
                    // 等待进程完成
                    process.WaitForExit();
                    WriteLog.Info(LogKind.Process, $"{startInfo.FileName} 已退出, 退出代码: {process.ExitCode}");
                    // 返回退出代码（0表示成功）
                    return process.ExitCode == 0;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"执行卸载命令时出错：{ex.Message}");
                return false;
            }
        }
        public static bool Taskkill(string task)
        {
            using (Process p = new Process())
            {
                p.StartInfo.FileName = "taskkill";
                p.StartInfo.Arguments = $"/f /im {task}";
                p.Start();
                p.WaitForExit();
                if (p.ExitCode != 0)
                {
                    WriteLog.Error(LogKind.Process, $"未能结束进程: {task} - {p.Id}");
                    return false;
                }
                else
                {
                    WriteLog.Info(LogKind.Process, $"已结束进程: {task} - {p.Id}");
                    return true;
                }
            }
        }
    }
}
